Chapter 4: Creating Our Backend Server

Now, it ’ s time to create the backend server! A single Django project can contain one or more apps that work

together to power an API. Django uses the concept of projects and apps to keep code clean and readable.

In the todobackend folder, create a new app ‘todo’ with the command:

Execute in Terminal

python3 manage.py startapp todo

A new folder todo will be added to the project. As we progress along the book, we will explain the files inside the

folder.

Though our new app exists in our Django project, Django doesn ’ t ‘ know ’ it till we explicitly add it. To do so, we

specify it in settings.py. So go to … /backend/settings.py, under INSTALLED_APPS, add the app name (shown in

bold):

Modify Bold Code

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'todo',

]

Models

Working with databases in Django involves working with models. We create a database model (e.g. todo, book,

blog post, movie) and Django turns these models into a database table for us. In … /backend/todo, you have the file

models.py where we create our models. Let’s create our todo model by filling in the following:

… /todo/models.py:

Replace Entire Code

from django.db import models

from django.contrib.auth.models import User

class Todo(models.Model):

title = models.CharField(max_length=100)

memo = models.TextField(blank=True)

#set to current time

created = models.DateTimeField(auto_now_add=True)

completed = models.BooleanField(default=False)

#user who posted this

user = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):

return self.title

Code Explanation

Analyze Code

from django.db import models

Django imports a module models to help us build database models which ‘ model ’ the characteristics of the data in

the database. In our case, we created a todo model to store the title, memo, time of creation, time of completion and

user who created the todo.

Analyze Code

class Todo(models.Model)

class Todo inherits from the Model class. The Model class allows us to interact with the database, create a table,

retrieve and make changes to data in the database.